package com.flute.icrawler.app.processor.extractor.special;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.flute.icrawler.htmlparser.impl.BasicHtmlParser;
import com.flute.icrawler.htmlparser.util.DOMUtil;
import com.flute.icrawler.app.entity.CrawlResult;
import com.flute.icrawler.app.util.ParameterKey;
import com.flute.icrawler.framework.framework.CrawlUrl;

public class TuDouCommentAlgo implements IExtractorBelongingsAlgo {
	private static Logger logger = Logger.getLogger(Ku6CommentAlgo.class);
	private static String commentUrl = "http://www.tudou.com/comments/itemcomment.srv?method=get&iid=";
	private static String pageXpath = "//DIV[@class='comment_list']/DIV/DIV[@class='lite']/SPAN[@class='count']";

	@Override
	public String[] extractor(CrawlUrl url) {
		String[] urls = null;
		try {
			CrawlResult crawlResult = (CrawlResult) url.getResultParameter(ParameterKey.RESULT_CRAWL).getValue();
			Document doc = new BasicHtmlParser().getDocument(new ByteArrayInputStream(crawlResult.getContent()));
			List<String> htmls = DOMUtil.getNodeHtml(doc, "//SCRIPT[1]");
			String videoId = this.getVideoID(htmls.get(0));
			int maxPage = this.getMaxPage(videoId);
			urls = new String[maxPage];
			for (int i = 1; i <= maxPage; i++) {
				urls[i - 1] = commentUrl + videoId + "&page=" + i;
			}
			return urls;
		} catch (Exception e) {
			logger.error(e);
		}
		return urls;
	}

	/**
	 * 获取视频ID
	 * 
	 * @param script
	 * @return
	 */
	private String getVideoID(String script) {
		String iid = null;
		Pattern p = Pattern.compile("\\,\\s*(defaultIid|iid)\\s*=\\s*(\\d+)\\s+\\,");
		Matcher m = p.matcher(script);
		if (m.find()) {
			iid = m.group(2);
		}
		return iid;
	}

	/**
	 * 
	 * @param videoID
	 * @return
	 */
	private int getMaxPage(String videoID) {
		int maxpage = 1;
		try {
			Document doc = new BasicHtmlParser().getDocument(commentUrl + videoID + "&page=1",
					BasicHtmlParser.HTML_STATIC);
			Node node = DOMUtil.xpath(doc, pageXpath).item(0);
			String pageValue = DOMUtil.getNodeValue(node);
			if (pageValue != null && !pageValue.trim().equals("")) {
				maxpage = Integer.parseInt(pageValue.substring(pageValue.lastIndexOf('/') + 1));
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return maxpage;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CrawlUrl url = new CrawlUrl(null, "http://www.tudou.com/playlist/playindex.do?lid=11158456");
		String[] s = new TuDouCommentAlgo().extractor(url);
		for (String a : s) {
			System.out.println(a);
		}

	}
}
